<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\Business;
use app\common\model\BusinessDistrictAdmin;
use app\common\model\PointsLog;
use app\common\model\ShopManage;
use app\common\model\User as Users;
use app\common\model\VisitLog;
use think\Validate;

class User extends BaseController
{

    /**
     * 更新微信信息
     */
    public function updateUser()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'nickname|昵称' => 'require',
            'portrait|头像' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user             = $this->request->user_info;
        $user->nickname   = $param['nickname'];
        $user->portrait   = $param['portrait'];
        $user->is_updated = 1;
        $user->save();
        return success($user);
    }

    /**
     * 更新用户手机号
     */
    public function updateUserPhone()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'encrypted_data|加密参数' => 'require',
            'iv|偏移量'              => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        //判断seesion_key
        if (!cache('?session_key' . $user_id)) {
            return error('session_key不存在,请用户重新登录');
        }
        $wechat      = new \Wechat();
        $re          = $wechat->decrypt($param['encrypted_data'], $param['iv'], cache('session_key' . $user_id));
        $user        = $this->request->user_info;
        $user->phone = $re['phoneNumber'];
        $user->is_updated = 1;
        $user->save();
        return success($user);
    }

    /**
     * 我的积分 以及收款二维码
     */
    public function myPoints()
    {
        $user_id              = $this->request->uid;
        $data['total_points'] = (new PointsLog())->getUsefulPoints($user_id);
        //生成收款码
        $qr_code         = (new \Wechat())->getUnlimitQRCode('pages/integral/give', $user_id);
        $data['qr_code'] = 'data:image/jpg;base64,' . base64_encode($qr_code);
        return success($data);
    }

    /**
     * 积分记录
     */
    public function pointsLog()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'type|类型' => 'require|in:1,2', //1:获取 2:兑换
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        [$page_size, $page_no] = paginate($param);
        $user_id = $this->request->uid;
        $log     = PointsLog::where('user_id', $user_id)->where('type', $param['type'])
            ->order('id', 'desc')
            ->limit($page_size * $page_no, $page_size)->select();
        foreach ($log as &$v) {
            switch ($v->flag) {
                case 1:
                    $v->type      = 1; //1:增加  2:减少
                    $v->type_name = "商家赠送";
                    break;
                case 2:
                    $v->type      = 2;
                    $v->type_name = "兑换商品";
                    break;
                case 5:
                    $v->type      = 1;
                    $v->type_name = "商家退款";
                    break;
                default:
                    $v->type      = 0;
                    $v->type_name = "未知";
                    break;
            }
        }
        return success($log);
    }

    /**
     * 获取个人信息
     */
    public function getUserInfo()
    {
        $user_id = $this->request->uid;
        $user    = Users::find($user_id);
        //禁用用户弹窗
        $user->is_updated = 1;
        return success($user);
    }

    /**
     * 个人中心页面数据
     */
    public function userCenter()
    {
        $user_id   = $this->request->uid;
        $user_info = $this->request->user_info;
        $desc      = [
            'shop_switch'          => 0,//店铺相关功能
            'shop_flag'            => 0,//店铺管理 0:不显示 1:显示
            'shop_admin_flag'      => 0,//店铺管理员  0:不显示 1:显示
            'shop_scan_flag'       => 0,//店铺扫一扫 0:不显示 1:显示
            'shop_notice_flag'     => 1,//店铺须知
            'shop_exit_flag'       => 1,//退出店铺
            'district_switch'      => 0,//商圈相关功能
            'district_flag'        => 0,//商圈管理  0:不显示 1:显示
            'district_admin_flag'  => 0, //商圈管理员 0:不显示 1:显示
            'district_shop_flag'   => 0, //商圈店铺  0:不显示 1:显示
            'district_exit_flag'   => 1,//退出商圈
            'district_notice_flag' => 1,//店铺须知
            'chain_switch'         => 0,//连锁功能
            'chain_flag'           => 0,//连锁管理
            'chain_shop'           => 0,//连锁店铺
            'chain_notice_flag'    => 1,//连锁须知
            'chain_exit_flag'      => 1,//退出连锁
        ];

        //查询用户 相关店铺权限
        $manage = ShopManage::where('user_id', $user_id)->where('status', 1)->select();
        if (!$manage->isEmpty()) {
            $desc['shop_switch'] = 1;
            foreach ($manage as $v) {
                if ($v->role == 1) {
                    $desc['shop_exit_flag'] = 0;
                }
                $arr = explode(',', $v['function_arr']);
                if (in_array(1, $arr)) {
                    $desc['shop_flag'] = 1;
                }
                if (in_array(2, $arr)) {
                    $desc['shop_admin_flag'] = 1;
                }
                if (in_array(3, $arr)) {
                    $desc['shop_scan_flag'] = 1;
                }
                if (in_array(4, $arr)) {
                    $desc['shop_scan_flag'] = 1;
                }
            }
        }
        //查询商圈相关
        $admin = BusinessDistrictAdmin::alias('da')
            ->join('pm_business_district d', 'da.district_id = d.id', 'right')
            ->where('d.type', 0)
            ->where('da.user_id', $user_id)
            ->field('da.*')
            ->find();
        if ($admin) {
            $desc['district_switch'] = 1;
            if ($admin->role == 1) {
                $desc['district_exit_flag'] = 0;
            }
            $arr = explode(',', $admin['function_arr']);
            if (in_array(1, $arr)) {
                $desc['district_flag'] = 1;
            }
            if (in_array(3, $arr)) {
                $desc['district_shop_flag'] = 1;
            }
            if (in_array(4, $arr)) {
                $desc['district_admin_flag'] = 1;
            }
        }
        //连锁相关
        $admin = BusinessDistrictAdmin::alias('da')
            ->join('pm_business_district d', 'da.district_id = d.id', 'right')
            ->where('d.type', 1)
            ->where('da.user_id', $user_id)
            ->field('da.*')
            ->find();
        if ($admin) {
            $desc['chain_switch'] = 1;
            if ($admin->role == 1) {
                $desc['chain_exit_flag'] = 0;
            }
            $arr = explode(',', $admin['function_arr']);
            if (in_array(1, $arr)) {
                $desc['chain_flag'] = 1;
            }
            if (in_array(3, $arr)) {
                $desc['chain_shop_flag'] = 1;
            }
        }
        $data = [
            'user_info' => [
                'id'       => $user_id,
                'nickname' => $user_info->nickname,
                'portrait' => $user_info->portrait,
                'phone'    => $user_info->phone,
            ],
            'icon'      => $desc
        ];
        return success($data);
    }

    /**
     * 用户搜索
     */
    public function UserSearch()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'phone|类型' => 'require', //根据用户昵称 获取用户列表
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user = \app\common\model\User::where('nickname', 'like', '%' . $param['phone'] . '%')
            ->where('role', 0)
            ->field('id,nickname,portrait,role,shop_id')
            ->select();
        if (!$user) {
            return error('当前用户不存在');
        }
        return success($user);
    }


    /**
     * 用户搜索
     */
    public function userSearchByPhone()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'phone|手机号' => 'require|mobile', //用户手机号
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user = \app\common\model\User::where('phone', $param['phone'])
            ->field('id,nickname,portrait,phone')
            ->order('id', 'desc')
            ->find();
        if (!$user) {
            return result([],'当前用户不存在',404);
        }
        return success($user);
    }

    /**
     * 用户搜索
     */
    public function userSearchById()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'user_id|用户id' => 'require|number', //用户id
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user = \app\common\model\User::where('id', $param['user_id'])
            ->field('id,nickname,portrait,phone')
            ->order('id', 'desc')
            ->find();
        if (!$user) {
            return error('当前用户不存在');
        }
        return success($user);
    }

    /**
     * 我的 浏览历史
     */
    public function visitLog()
    {
        $param   = $this->request->param();
        $user_id = $this->request->uid;
        [$pageSize, $page] = paginate($param);

        $data = VisitLog::with('shop')->where('user_id', $user_id)->group('shop_id')->order('id', 'desc')->limit($pageSize * $page, $pageSize)->select();
        return success($data);
    }

    /**
     * 浏览历史删除
     */
    public function visitLogDelete()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        VisitLog::where('shop_id', $param['shop_id'])->update(['delete_time' => time()]);
        return success([], '删除成功');
    }
}